<template>
	<div class="layouts-menu-horizontal">
		<div v-if="webConfigStore.layout.menuShowTopBar" class="menu-horizontal-logo">
			<Logo/>
		</div>
		<el-scrollbar ref="horizontalMenusRef" class="horizontal-menus-scrollbar">
			<el-menu :key="state.menuKey" :default-active="state.defaultActive" class="menu-horizontal" mode="horizontal">
				<MenuTree :menus="menus"/>
			</el-menu>
		</el-scrollbar>
		<NavMenus/>
	</div>
</template>

<script lang="ts" setup>
import {computed, nextTick, onMounted, reactive, ref} from 'vue'
import Logo from '../logo.vue'
import MenuTree from '../menuTree.vue'
import {onBeforeRouteUpdate, type RouteLocationNormalizedLoaded, useRoute} from 'vue-router'
import {useWebConfigStore} from '@/stores/modules/webConfig.store'
import type {ScrollbarInstance} from 'element-plus'
import NavMenus from '@/layouts/components/navBar/components/navMenus.vue'
import {uuid} from '@/utils/randomUtil'
import {useUserStore} from '@/stores/modules/user.store'

const horizontalMenusRef = ref<ScrollbarInstance>()

const userStore = useUserStore()
const webConfigStore = useWebConfigStore()
const route = useRoute()

const state = reactive({
	menuKey: uuid(),
	defaultActive: ''
})

const menus = computed(() => {
	state.menuKey = uuid()
	return userStore.menus
})

// 激活当前路由的菜单
const currentRouteActive = (currentRoute: RouteLocationNormalizedLoaded) => {
	state.defaultActive = currentRoute.path
}

// 滚动条滚动到激活菜单所在位置
const verticalMenusScroll = () => {
	nextTick(() => {
		let activeMenu: HTMLElement | null = document.querySelector('.el-menu.menu-horizontal li.is-active')
		if (!activeMenu) return false
		horizontalMenusRef.value?.setScrollTop(activeMenu.offsetTop)
	})
}

onMounted(() => {
	currentRouteActive(route)
	verticalMenusScroll()
})

onBeforeRouteUpdate((to) => {
	currentRouteActive(to)
})
</script>

<style lang="scss" scoped>
.layouts-menu-horizontal {
	align-items: center;
	background-color: var(--cus-bg-color-overlay);
	border-bottom: solid 1px var(--el-color-info-light-8);
	display: flex;
	height: 60px;
	width: 100vw;
}

.menu-horizontal-logo {
	width: 180px;

	&:hover {
		background-color: v-bind('webConfigStore.getColorVal("headerBarHoverBackground")');
	}
}

.horizontal-menus-scrollbar {
	flex: 1;
}

.menu-horizontal {
	border: none;
	--el-menu-active-color: v-bind('webConfigStore.getColorVal("menuActiveColor")');
	--el-menu-bg-color: v-bind('webConfigStore.getColorVal("menuBackground")');
	--el-menu-text-color: v-bind('webConfigStore.getColorVal("menuColor")');
}

.el-sub-menu .icon,
.el-menu-item .icon {
	margin-right: 5px;
	text-align: center;
	vertical-align: middle;
	width: 24px;
}

.is-active .icon {
	color: var(--el-menu-active-color) !important;
}

.el-menu-item.is-active {
	background-color: v-bind('webConfigStore.getColorVal("menuActiveBackground")');
}
</style>
